package common

import (
	"flag"
	"os"
	"path/filepath"
	"runtime"
	"strings"
)

const (
	DEV  = "dev"
	TEST = "test"
	PROD = "prod"
)

var (
	//是否go run运行
	isGoRun bool
	//是否go test运行
	GOPATH      string = os.Getenv("GOPATH")
	isGoTest    bool
	PID         = os.Getpid()
	HOSTNAME, _ = os.Hostname()

	appPath = getAppPath()
	APPPATH = GetAppPath()
	//ENVIRONMENT 环境
	ENVIRONMENT string
)

func ParseFlag() (err error) {
	flag.StringVar(&ENVIRONMENT, "e", "", "set env, e.g dev test prod")

	var help bool
	flag.BoolVar(&help, "help", false, "print help and usage infomation")

	flag.Parse()

	if help {
		flag.Usage()
		os.Exit(0)
	}

	if len(ENVIRONMENT) == 0 {
		ENVIRONMENT = os.Getenv("ENVIRONMENT")
	}
	if len(ENVIRONMENT) == 0 && (IsGoRun() || IsGoTest()) {
		ENVIRONMENT = DEV
	}
	return
}

func GetAppPath() string {
	return appPath
}

func getAppPath() (appPath string) {
	var err error
	pwd, _ := filepath.Abs(os.Args[0])
	if strings.Contains(pwd, "go-build") {
		pwd = stripSuffix(pwd)
		if strings.HasSuffix(pwd, ".test") {
			isGoTest = true
		} else {
			isGoRun = true
		}
		appPath, err = os.Getwd()
		if err != nil {
			panic(err)
		}
		minLen := 1
		if runtime.GOOS == "windows" {
			minLen = 3
		}
		for {
			if IsExist(filepath.Join(appPath, "config")) ||
				IsExist(filepath.Join(appPath, "main.go")) ||
				IsExist(filepath.Join(appPath, "controllers")) {
				return
			} else {
				if len(appPath) <= minLen {
					return
				}
				appPath = filepath.Dir(appPath)
			}
		}
	} else {
		appPath = filepath.Dir(pwd)
	}

	return
}

func stripSuffix(path string) string {
	if runtime.GOOS == "windows" {
		path = strings.TrimSuffix(path, ".exe")
	}

	return path
}

func GetPid() int {
	return PID
}

func GetHostName() string {
	return HOSTNAME
}

func IsProdEnv() bool {
	return ENVIRONMENT == PROD
}

func IsTestEnv() bool {
	return ENVIRONMENT == TEST
}

func IsDevEnv() bool {
	return ENVIRONMENT == DEV
}

func IsGoRun() bool {
	return isGoRun
}

func IsGoTest() bool {
	return isGoTest
}
